package com.atguigu.gmall.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.item.client.ItemFeignClient;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
public class ItemController {

    @Autowired
    private ItemFeignClient itemFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 远程调用获取数据汇总
     * @param skuId
     * @param model
     * @return
     */
    @RequestMapping("/{skuId}.html")
    public String getItem(@PathVariable Long skuId, Model model){
        // 通过skuId 查询skuInfo
        Result<Map<String, Object>> result = itemFeignClient.getItem(skuId);
        Map<String, Object> data = result.getData();
        if(null==data||data.get("skuInfo")==null){
            return "error/index.html";
        }
        // 整个 Map 数据整体全部存入 Model，Map 的 Key 就是请求域中数据的属性名
        model.addAllAttributes(result.getData());
        return "item/index1.html";
    }

    @GetMapping({"/", "/index.html"})
    public String showPortal(Model model) {
        Result<List<JSONObject>> result = productFeignClient.getAllCategoryForPortal();
        List<JSONObject> allCategoryList = result.getData();
        model.addAttribute("list", allCategoryList);
        return "index/index.html";
    }
}
